<?php
class ClientHandler
{
	public static function changeGroup($iClientgroup, $sName) {
		try {
			DataHandler::query("
				UPDATE clientgroups
				SET name = ?
				WHERE id = ?
			", $sName, $iClientgroup);

			return true;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function delGroup($iClientgroup) {
		try {
			DataHandler::beginTransaction();
			
			DataHandler::query("
				DELETE FROM clientgroups_users
				WHERE group_id = ?
			", $iClientgroup);
			
			DataHandler::query("
				DELETE FROM clientgroups
				WHERE id = ?
			", $iClientgroup);
			
			DataHandler::commit();
			
			return true;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function addGroup($sName) {
		try {
			DataHandler::beginTransaction();
			
			DataHandler::query("
				INSERT INTO clientgroups (
					name
				) VALUES (
					?
				)
			", $sName);
			
			$iNewID = DataHandler::lastInsertId();

			DataHandler::query("
				INSERT INTO clientgroups_users (
					group_id,
					user_id,
					access
				) VALUES (
					?,
					?,
					?
				)
			", $iNewID, $_SESSION['rid'], 'admin');
			
			DataHandler::commit();
			
			return $iNewID;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	// A handy public static function, just for getting client names, mapped by serial.
	public static function getClientNames() {
		try {
			if (@is_array($GLOBALS['client']['clientnames']))
			{
				return $GLOBALS['client']['clientnames'];
			}
			
			$oQuery = DataHandler::query("
				SELECT
					serial,
					name
				FROM clients
			");
			
			$GLOBALS['client']['clientnames'] = array();
			while (list($sSerial, $sName) = $oQuery->fetch(PDO::FETCH_NUM))
			{
				$GLOBALS['client']['clientnames'][$sSerial] = $sName;
			}
			return $GLOBALS['client']['clientnames'];
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function delUser($iClientgroup, $iUser)
	{
		try {
			if ($iUser == $_SESSION['rid']) {
				throw new MiJobException('Cannot delete self');
			}
			
			DataHandler::query("
				DELETE FROM clientgroups_users
				WHERE group_id = ?
				AND user_id = ?
			", $iClientgroup, $iUser);
			
			return true;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function changeUser($iClientgroup, $iUser, $bAdmin)
	{
		try {
			if ($iUser == $_SESSION['rid']) {
				throw new MiJobException('Cannot change self');
			}
			
			DataHandler::query("
				UPDATE clientgroups_users
				SET access = ?
				WHERE group_id = ?
				AND user_id = ?
			", ($bAdmin ? 'admin' : 'user'), $iClientgroup, $iUser);
			
			return 1;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function addUser($iClientgroup, $iUser, $bAdmin) {
		try {
			$oCheckQuery = DataHandler::query("
				SELECT id
				FROM clientgroups_users
				WHERE user_id = ?
				AND group_id = ?
			", $iUser, $iClientgroup);

			if ($oCheckQuery->rowCount()) {
				throw new MiJobException('User already has access to this clientgroup');
			}

			DataHandler::query("
				INSERT INTO clientgroups_users (
					group_id,
					user_id,
					access
				) VALUES (
					?,
					?,
					?
				)
			", $iClientgroup, $iUser, ($bAdmin ? 'admin' : 'user'));

			$iNewID = DataHandler::lastInsertId();
			return $iNewID;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}

	public static function getAdmins($iClientgroup)
	{
		$sUsers = ClientHandler::getUsers($iClientgroup);
		$iAdmins = array();
		foreach ($sUsers as $iUser => $sAccess)
		{
			if ($sAccess == 'admin')
			{
				array_push($iAdmins, $iUser);
			}
		}
		return $iAdmins;
	}
	
	public static function getUsers($iClientgroup)
	{
		try {
			if (is_array(@$GLOBALS['client']['users']))
			{
				return $GLOBALS['client']['users'];
			}
			
			$oQuery = DataHandler::query("
				SELECT
					cu.user_id,
					cu.access
				FROM
					clientgroups_users cu,
					".DATA_USERBASE.".users u
				WHERE cu.user_id = u.id
				AND cu.group_id = ?
				ORDER BY u.user
			", $iClientgroup);

			$GLOBALS['client']['users'] = array();
			while (list($iUser, $sAccess) = $oQuery->fetch(PDO::FETCH_NUM))
			{
				$GLOBALS['client']['users'][$iUser] = $sAccess;
			}
			return $GLOBALS['client']['users'];
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function delClient($iClientgroup, $iClient)
	{
		try {
			DataHandler::query("
				DELETE FROM clients
				WHERE id = ?
				AND group_id = ?
			", $iClient, $iClientgroup);

			return true;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function changeClient($iClientgroup, $iClient, $sName, $sSerial, $iNewClientgroup, $bUpdateWork)
	{
		try {
			if (!$sName) {
				throw new MiJobException('Client must have name');
			}
			
			if (!$sSerial) {
				throw new MiJobException('Client must have serial');
			}

			$oSerialQuery = DataHandler::query("
				SELECT serial
				FROM clients
				WHERE group_id = ?
				AND id = ?
			", $iClientgroup, $iClient);

			list($sOldSerial) = $oSerialQuery->fetch(PDO::FETCH_NUM);

			$oCheckQuery = DataHandler::query("
				SELECT id
				FROM clients
				WHERE (
					group_id = ?
					OR group_id = ?
				)
				AND serial = ?
				AND id != ?
			", $iClientgroup, $iNewClientgroup, $sSerial, $iClient);

			if ($oCheckQuery->rowCount() > 0) {
				throw new MiJobException('Client already exists');
			}

			DataHandler::query("
				UPDATE clients
				SET
					name = ?,
					serial = ?,
					group_id = ?
				WHERE id = ?
				AND group_id = ?
			", $sName, $sSerial, $iNewClientgroup, $iClient, $iClientgroup);

			if ($bUpdateWork) {
				$iBeginningOfMonth = mktime(0, 0, 0, date('n'), 1, date('Y'));

				DataHandler::query("
					UPDATE work
					SET
						worknumber = ?,
						sent = '1'
					WHERE worknumber = ?
					AND starttime > ?
					AND (
						sent = '0'
						OR sent = '1'
					)
				", $sSerial, $sOldSerial, $iBeginningOfMonth);
			}

			return true;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function addClient($iClientgroup, $sName, $sSerial)
	{
		try {
			if (!$sName) {
				throw new MiJobException('Client must have name');
			}
			
			if (!$sSerial) {
				throw new MiJobException('Client must have serial');
			}
			
			$oCheckQuery = DataHandler::query("
				SELECT id
				FROM clients
				WHERE group_id = ?
				AND serial = ?
			", $iClientgroup, $sSerial);

			if ($oCheckQuery->rowCount() > 0)
			{
				throw new MiJobException('Client already exists');
			}

			DataHandler::query("
				INSERT INTO clients (
					name,
					serial,
					group_id
				) VALUES (
					?,
					?,
					?
				)
			", $sName, $sSerial, $iClientgroup);
			
			$iNewID = DataHandler::lastInsertId();
			
			return $iNewID;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function getAccess($iClientgroup)
	{
		try {
			if (is_string(@$GLOBALS['client']['groupaccess'][$iClientgroup]))
			{
				return $GLOBALS['client']['groupaccess'][$iClientgroup];
			}
			
			$oQuery = DataHandler::query("
				SELECT access
				FROM clientgroups_users
				WHERE user_id = ?
				AND group_id = ?
			", $_SESSION['rid'], $iClientgroup);
			
			list($GLOBALS['client']['groupaccess'][$iClientgroup]) = $oQuery->fetch(PDO::FETCH_NUM);
			return (string)$GLOBALS['client']['groupaccess'][$iClientgroup];
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function getClientgroups()
	{
		try {
			if (@is_array($GLOBALS['client']['clientgroup']))
			{
				return $GLOBALS['client']['clientgroup'];
			}
			
			$oUsers = UserHandler::getUsers();
			$oQuery = DataHandler::query("
				SELECT
					cg.id,
					cg.name
				FROM
					clientgroups cg,
					clientgroups_users cg_u
				WHERE cg_u.user_id = ?
				AND cg_u.group_id = cg.id
				ORDER BY cg.name
			", $_SESSION['rid']);

			$GLOBALS['client']['clientgroup'] = array();
			while (list($iID, $sName) = $oQuery->fetch(PDO::FETCH_NUM))
			{
				$mEntity = array();
				$mEntity['iID'] = $iID;
				$mEntity['sName'] = $sName;
				$GLOBALS['client']['clientgroup'][$iID] = (object)$mEntity;
			}
			return $GLOBALS['client']['clientgroup'];
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
	
	public static function getClients($iGroup = 0)
	{
		try {
			$oQuery = DataHandler::query("
				SELECT
					c.id,
					c.name,
					c.serial,
					c.group_id
				FROM
					clients c,
					clientgroups_users cg_u
				WHERE
					cg_u.user_id = ?
					AND cg_u.group_id = c.group_id
					AND (
						? = 0
						OR c.group_id = ?
					)
				ORDER BY c.name
			", $_SESSION['rid'], $iGroup, $iGroup);

			$oClients = array();
			while (list($iID, $sName, $sSerial, $iGroup) = $oQuery->fetch(PDO::FETCH_NUM))
			{
				$oClients[$iID] = new Client($iID, $sName, $sSerial, $iGroup);
			}
			return $oClients;
		}
		catch (Exception $e) {
			ErrorHandler::addError($e->getMessage());
		}
	}
}
?>
